package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.consts.GmallConsts;
import com.atguigu.gmall.order.vo.PayOrderVO;
import com.atguigu.gmall.payment.bean.PaymentInfoEntity;
import com.atguigu.gmall.payment.config.GmallAlipayConfig;
import com.atguigu.gmall.payment.feign.GmallOmsClient;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
@Slf4j
public class PaymentServiceImpl implements PaymentService {
    @Resource
    GmallOmsClient omsClient;
    @Resource
    PaymentInfoMapper paymentInfoMapper;
    @Resource
    RabbitTemplate rabbitTemplate;
    @Override
    public PayOrderVO queryOrder(String orderToken) {
        PayOrderVO payOrderVO = omsClient.queryPayOrderVOByOrderToken(orderToken).getData();
        return payOrderVO;
    }

    @Override
    public String nofityUrl(HttpServletRequest request) {
        try {
            Map<String, String> params = getStringStringMap(request);
            System.out.println("异步回调参数："+params);
            boolean signVerified = AlipaySignature.rsaCheckV1(params, GmallAlipayConfig.alipay_public_key,
                    GmallAlipayConfig.charset, GmallAlipayConfig.sign_type); //调用SDK验证签名

            //——请在这里编写您的程序（以下代码仅作参考）——

        /* 实际验证过程建议商户务必添加以下校验：
            0、签名校验
            1、幂等性校验： 本地交易日志状态是否为已更新状态
            2、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            3、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            4、验证app_id是否为该商户本身。
        */
            if(signVerified) {//验证成功
                //商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
                //幂等性校验
                PaymentInfoEntity paymentInfoEntity = paymentInfoMapper.selectOne(Wrappers.lambdaQuery(PaymentInfoEntity.class)
                        .eq(PaymentInfoEntity::getOutTradeNo, out_trade_no));
                if(paymentInfoEntity==null){
                    log.error("异步回调,订单编号错误:{}", JSON.toJSONString(params) );
                    return "fail";//订单不是我们的
                }
                if(paymentInfoEntity.getPaymentStatus()==1){
                    //订单状态已更新
                    return "success";
                }
                //校验支付金额
                String buyer_pay_amount = new String(request.getParameter("buyer_pay_amount").getBytes("ISO-8859-1"),"UTF-8");
                if(paymentInfoEntity.getTotalAmount().compareTo(new BigDecimal(buyer_pay_amount))!=0){
                    //支付金额不一致
                    log.error("异步回调,实付金额错误:{}", JSON.toJSONString(params));
                    return "fail";
                }
                //校验app_id是否正确
                String app_id = new String(request.getParameter("app_id").getBytes("ISO-8859-1"),"UTF-8");
                if(!GmallAlipayConfig.app_id.equals(app_id)){
                    log.error("异步回调,回调appid错误:{}", JSON.toJSONString(params));
                    return "fail";
                }
                String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
                //校验支付状态是否为成功
                if(!trade_status.equals("TRADE_SUCCESS")){
                    log.error("异步回调,支付状态异常:{}", JSON.toJSONString(params));
                    return "fail";
                }
                //成功：
                //1、更新本地日志的信息
                paymentInfoEntity.setPaymentStatus(1);
                //支付宝交易号
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
                paymentInfoEntity.setTradeNo(trade_no);
                paymentInfoEntity.setCallbackContent( JSON.toJSONString(params));
                String notify_time = new String(request.getParameter("notify_time").getBytes("ISO-8859-1"),"UTF-8");
                Date callbackTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(notify_time);
                paymentInfoEntity.setCallbackTime(callbackTime);
                paymentInfoMapper.updateById(paymentInfoEntity);
                //2、更新订单状态
                //   更新库存
                //发送mq消息：  oms服务(orderToken、支付时间、支付方式)     wms更新库存销量(orderToken: 查询锁库存的缓存)
                Map<String,Object> map = new HashMap<>();
                map.put("orderToken",out_trade_no);
                map.put("paymentTime" ,callbackTime );
                map.put("payType", 1);
                rabbitTemplate.convertAndSend(GmallConsts.MQ_ORDER_EXCHANGE,
                        "trade.success" ,map );
                return "success";
            }
            // 异步回调中修改订单的支付状态+修改库存和销量
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }

    public Map<String, String> getStringStringMap(HttpServletRequest request) throws UnsupportedEncodingException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }

    @Override
    public String returnUrl(HttpServletRequest request) {
        try {
            //获取支付宝GET过来反馈信息
            Map<String, String> params = getStringStringMap(request);
            System.out.println("回调参数列表："+params);
            //1、验证支付成功同步回调参数的签名是否正确
            boolean signVerified = AlipaySignature.rsaCheckV1(params, GmallAlipayConfig.alipay_public_key,
                    GmallAlipayConfig.charset, GmallAlipayConfig.sign_type); //调用SDK验证签名

            if(signVerified) {
                //2、签名正确：参数没有被篡改
                //商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
                //支付宝交易号
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
                //付款金额
                String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
                //3、查询out_trade_no订单的应付金额 和 用户在支付宝中实际支付的金额比较
                PaymentInfoEntity paymentInfoEntity = paymentInfoMapper.selectOne(Wrappers.lambdaQuery(PaymentInfoEntity.class)
                        .eq(PaymentInfoEntity::getOutTradeNo, out_trade_no));
                if(paymentInfoEntity!=null && paymentInfoEntity.getTotalAmount().compareTo(new BigDecimal(total_amount))==0){
                    //签名、支付金额正确  跳转到支付成功页面
                    request.setAttribute("total_amount", total_amount);
                    return "paysuccess";//转发到支付成功页
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        //参数 签名  支付金额验证可能失败
        //抛出自定义异常
        /*
            @ControllerAdvice标注的异常处理器：
                该异常处理器处理异常后进行转发或者重定向到失败页
                自定义转发异常处理器处理的异常类型
            @RestControllerAdvice异常处理器：
                该异常处理器处理异常后将响应数据转为json字符串响应(使用统一响应类处理)
                 自定义REST风格异常处理器处理的异常类型
         */
        return "error";//跳转到支付失败页面
    }
}
